java


A variable is a named memory location used to store data during program execution.

Java is case-sensitive (HelloWorld and helloworld are different). main method is the entry point of the program.

Syntax
dataType variableName = value;

Example:
int age = 25;
String name = "Alice";


Rules for Naming Variables
Must start with a letter, $, or _ (cannot start with a digit).

Cannot use reserved keywords like class, public, etc.

Java is case-sensitive (count and Count are different variables) 

Data Types in Java

Java is strongly typed, meaning every variable must have a declared type.

These store simple values directly in memory.

Data Type	Size	Example	Description
byte	1 byte	byte b = 10;	Small integers (-128 to 127)
short	2 byte	short s = 200;	Small integers
int	4 byte	int x = 1000;	Default integer type
long	8 byte	long l = 100000L;	Large integers
float	4 byte	float f = 3.14f;	Decimal numbers (single precision)
double	8 byte	double d = 3.14159;	Decimal numbers (double precision)
char	2 byte	char c = 'A';	Single characters
boolean	1 bit	boolean flag = true; 

Non-Primitive (Reference) Data Types

These store references to objects rather than the data itself. Examples: String, arrays, classes, interfaces.

String message = "Hello, Java!";
 

Type Casting in Java

Type casting is converting a variable from one data type to another.


Widening Casting (Implicit)

Automatically converts a smaller type to a larger type.

No data loss.

 
int num = 10;
double d = num;  // int → double
System.out.println(d); // 10.0 

Narrowing Casting (Explicit)

Manually converts a larger type to a smaller type. May result in data loss.

double pi = 3.14159;
int intPi = (int) pi;  // double → int
System.out.println(intPi); // 3
 

Example Program

public class TypeCastingExample {
    public static void main(String[] args) {
        // Variables
        int age = 25;
        double salary = 55000.75;
        char grade = 'A';
        boolean isJavaFun = true;

        // Widening Casting
        int num = 100;
        double widened = num;

        // Narrowing Casting
        double pi = 3.14159;
        int narrowed = (int) pi;

        // Output
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Grade: " + grade);
        System.out.println("Java Fun? " + isJavaFun);
        System.out.println("Widened Value: " + widened);
        System.out.println("Narrowed Value: " + narrowed);
    }
}